import React from "react";
import { Button, Table, Card, Modal, Form, Input, message, Upload } from "antd";
import { FormOutlined, DeleteOutlined, LoadingOutlined, PlusOutlined} from "@ant-design/icons";
import { Pagination } from "antd";
import { useEffect, useState } from "react";
import AttrApi, { AttrList } from "@/api/trademark/Attr";
import type { UploadChangeParam } from "antd/es/upload";
import type { RcFile, UploadFile, UploadProps } from "antd/es/upload/interface";

export default function Attr() {
  let [pageInfoList, setPageInfoList] = useState<AttrList[]>([
    { id: 0, tmName: "", logoUrl: "" },
  ]);
  //分页
  let [total, setTotal] = useState<number>(0);
  let [current, setCurrent] = useState<number>(1);
  let [pageSize, setPageSize] = useState<number>(3);
  const getInfoList = async (page: number, limit: number) => {
    const result = await AttrApi.getPageListInfo(page, limit);
    setPageInfoList(result.records);
    setTotal(result.total);
    setCurrent(result.current);
    setPageSize(result.size);
    console.log(result);
  };
  useEffect(() => {
    getInfoList(current, pageSize);
  }, [current, pageSize]);

  //获取输入名称
  const handleNameChange = (e: any) => {
    setTmName(e.target.value);
  };
  const [tmName, setTmName] = useState("");
  const [logoUrl, setLogoUrl] = useState("");
  const [id, setId] = useState("");
  const showUpdata = (row: AttrList) => {
    return () => {
      //弹出对话框
      setIsModalOpen(true);
      const attr = { ...row };
      setId(attr.id as any);
      setImageUrl(attr.logoUrl);
      setTmName(attr.tmName);
    };
  };
  const columns = [
    {
      title: "序号",
      dataIndex: "id",
    },
    {
      title: "品牌名称",
      dataIndex: "tmName",
    },
    {
      title: "品牌LOGO",
      dataIndex: "logoUrl",
      render: (data: string) => {
        return <img width="70" src={data} alt="" />;
      },
    },
    {
      title: "操作",
      render: (row: AttrList) => {
        return (
          <div>
            <Button
              type="primary"
              onClick={showUpdata(row)}
              icon={<FormOutlined />}
            >
              修改
            </Button>

            <Button
              type="primary"
              style={{ marginLeft: "10px" }}
              danger
              onClick={deleteAttr(row)}
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </div>
        );
      },
    },
  ];
  const [isModalOpen, setIsModalOpen] = useState(false);
  //弹框
  const showModal = () => {
    setIsModalOpen(true);

  };

  //添加
  const handleOk = async () => {
    if (id) {
      await AttrApi.addOrUpdate({ id, tmName, logoUrl });
      message.success("修改成功");
      
    } else {
      await AttrApi.addOrUpdate({ tmName, logoUrl });
      message.success("添加成功");
    }
    getInfoList(current, pageSize);

    // console.log(tmName);
    setIsModalOpen(false);
  };
  //删除
  const deleteAttr = (row: AttrList) => {
    return async () => {
      await AttrApi.remove(row.id as number);
      getInfoList(current, pageSize);
      message.success("删除成功");
    };
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  //上传图片
  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener("load", () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };

  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("Image must smaller than 2MB!");
    }
    return isJpgOrPng && isLt2M;
  };

  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();

  const handleChange: UploadProps["onChange"] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    console.log(info);
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, (url) => {
        setLoading(false);
        //获取图片
        setImageUrl(url);
        setLogoUrl(info.file.response.data);
      });
      // console.log('123',getBase64);
      
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}></div>
    </div>
  );

  return (
    <div>
      <Card>
        <Button
          type="primary"
          onClick={showModal}
          style={{ margin: "0 30px" }}
          icon={<PlusOutlined />}
        >
          添加
        </Button>
        <Modal
          title="添加品牌"
          visible={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <Form
            wrapperCol={{ span: 18 }}
            initialValues={{ remember: true }}
            autoComplete="off"
          >
            <Form.Item
              label="品牌名称"
              rules={[
                { required: true, message: "Please input your username!" },
              ]}
            >
              <Input value={tmName} onChange={handleNameChange} />
            </Form.Item>
            <Form.Item
              label="品牌LOGO"
              rules={[
                { required: true, message: "Please input your username!" },
              ]}
            >
              <Upload
                style={{ width: "200", height: "200" }}
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="/app-dev/admin/product/upload"
                beforeUpload={beforeUpload}
                onChange={handleChange}
              >
                {imageUrl ? (
                  <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
                ) : (
                  uploadButton
                )}
              </Upload>
              <div>上传的图片必须是jpg且不能大于2M</div>
            </Form.Item>
          </Form>
        </Modal>
        <Table
          pagination={false}
          dataSource={pageInfoList}
          rowKey="id"
          columns={columns}
        />
        <Pagination
          style={{ marginTop: "50px" }}
          current={current}
          total={total}
          showSizeChanger
          showQuickJumper
          pageSize={pageSize}
          pageSizeOptions={[3, 5, 7, 9]}
          showTotal={(total) => `总共 ${total} 条`}
          onChange={(page, limit) => {
            setCurrent(page);
          }}
          onShowSizeChange={(page, limit) => {
            setPageSize(limit);
          }}
        />
      </Card>
    </div>
  );
}




















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































